﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ASPNETPerformance.App_BusinessLogic.Data;
using ASPNETPerformance.App_BusinessLogic.Extensions;

namespace ASPNETPerformance.Services {
    /// <summary>
    /// NorthwindService 的摘要说明
    /// </summary>
    public class NorthwindService : IHttpHandler {

        public void ProcessRequest( HttpContext context ) {
            // must format ~/Services/NorthwindService.ashx/ACTION/ID

            context.Response.ContentType = "application/json";

            string output = string.Empty;

            // 使用 "/" 分隔 PathInfo
            var parts = context.Request.PathInfo.Split( "/".ToCharArray() );
            if ( parts.Length == 0 )
                throw new ArgumentException( "格式化错误" );

            if ( string.CompareOrdinal( parts[ 1 ], "GetCategories" ) == 0 ) {
                using ( var dbContext = new NORTHWNDEntities() ) {
                    var categories = from category in dbContext.Categories
                                     orderby category.CategoryName
                                     select new {
                                         category.CategoryID,
                                         category.CategoryName,
                                         category.Description
                                     };

                    output = categories.ToJson();
                }
            }
            else if ( string.CompareOrdinal( parts[ 1 ], "GetProductsByCategory" ) == 0 ) {
                if ( parts.Length == 2 )
                    throw new ArgumentException( "必须使用/GetProductsByCategory/ID" );

                int categoryId = 0;
                bool idIsInt = int.TryParse( parts[ 2 ], out categoryId );
                if ( !idIsInt )
                    throw new ArgumentException( string.Format( "ID  '{0}' 不是整数", parts[ 2 ] ) );

                using ( var dbContext = new NORTHWNDEntities() ) {
                    var products = from product in dbContext.Products
                                   where product.CategoryID == categoryId
                                   orderby product.ProductName
                                   select new {
                                       product.ProductName,
                                       product.QuantityPerUnit,
                                       product.UnitPrice,
                                       product.Discontinued
                                   };

                    output = products.ToJson();
                }
            }
            else
                throw new ArgumentException( "" );


            //  输出Json字符串
            context.Response.Write( output );

        }

        public bool IsReusable {
            get {
                return false;
            }
        }
    }
}